package cn.tedu.sp11.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //过滤器类型：pre前置   post后置    routing路由   error错误过滤器
    @Override
    public String filterType() {
       // return "pre";
        return FilterConstants.PRE_TYPE;
    }

    //过滤器插入位置
    //在第5个过滤器中在上下文对象添加了 serviceId
    //在后面过滤器中才能访问serviceId
    @Override
    public int filterOrder() {
        return 6;
    }
    //对用户请求进行判断，判断是否执行过滤代码
    @Override
    public boolean shouldFilter() {
        /*
        只对item-service调用进行过滤
        如果后台调用user-service或order-service 不执行过滤代码
         */
       //获得调用的服务id
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equalsIgnoreCase(serviceId);
    }

    //过滤代码
    @Override
    public Object run() throws ZuulException {
       /*
       http://localhost:3001/item-service/54y54y  没有登录，不允许访问
        http://localhost:3001/item-service/54y54y?token=3t3t3t  已登录
        */
        //获得request对象
        RequestContext ctx=RequestContext.getCurrentContext();
        HttpServletRequest request=ctx.getRequest();

        //接收token参数
        String token=request.getParameter("token");

        //如果没有token，阻止访问，并直接向客户端返回响应
        if (StringUtils.isBlank(token)){
            //阻止访问
            ctx.setSendZuulResponse(false);
            //JsonResult{code:401,message:not login,data:null}
            String json=
            JsonResult.err()
                    .code(JsonResult.NOT_LOGIN)
                    .msg("not login")
                    .toString();
            ctx.addZuulResponseHeader("Content-Type","application/json;charset=UTF-8" );
            ctx.setResponseBody(json);
        }
            return null;//返回值没有任何作用
    }
}
